<template>
  <el-card>
    <!-- 操作区域：新增 + 搜索 -->
    <div style="margin-bottom: 16px; display: flex; align-items: center; justify-content: space-between;">
      <div style="display: flex; align-items: center">
        <el-button type="primary" @click="showAddDialog = true" style="margin-right: 10px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1)">+添加问题</el-button>
        <el-input
            v-model="searchQuery"
            placeholder="请输入问题关键词"
            style="width: 240px; margin-left: 16px; border-radius: 4px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1)"
            clearable
        >
          <i slot="suffix" class="el-input__icon el-icon-search" style="color: #666;"></i>
            @input="handleSearch"
        </el-input>
      </div>
    </div>

    <!-- 表格 -->
    <el-table :data="paginatedFaqs" border stripe style="text-align: left; table-layout: fixed;">
      <el-table-column prop="question" label="问题" min-width="200" />
      <el-table-column prop="answer" label="答案" min-width="300" />
      <el-table-column label="操作" min-width="120">
        <template #default="{ row }">
          <el-button type="success" size="small" @click="handleEdit(row)" style="margin-right: 5px;">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        layout="sizes, prev, pager, jumper, next"
        :total="filteredFaqs.length"
        :page-size="pageSize"
        :current-page="currentPage"
        :page-sizes="[5, 10,15]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        active-text-color="#409EFF"
        style="margin-top: 16px; text-align: left"
    />

    <!-- 弹窗 -->
    <el-dialog :title="editMode ? '编辑问题' : '添加问题'" :visible.sync="showAddDialog" width="60%">
      <el-form ref="faqForm" :model="currentFaq" :rules="faqRules" label-width="80px">
        <el-form-item label="问题" prop="question">
          <el-input v-model="currentFaq.question" placeholder="请输入问题内容" />
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-input type="textarea" v-model="currentFaq.answer" placeholder="请输入答案内容" rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false" aria-label="取消当前操作">取消</el-button>
        <el-button type="primary" @click="handleSave" aria-label="保存当前问题">保存</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
import { ref, reactive, computed, onMounted } from '@vue/composition-api'
import { Loading } from 'element-ui';
import axios from 'axios'
import { Message } from 'element-ui'

export default {
  setup() {
    const faqList = ref([])
    const searchQuery = ref('')
    const currentPage = ref(1)
    const pageSize = ref(5)

    // 过滤后的列表（搜索）\n    const handleSearch = () => {\n      currentPage.value = 1;\n    }\n    
    const filteredFaqs = computed(() => {
      return faqList.value.filter(item =>
          item.question.toLowerCase().includes(searchQuery.value.toLowerCase())
      )
    })

    // 分页后展示的数据
    const paginatedFaqs = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return filteredFaqs.value.slice(start, end)
    })

    const showAddDialog = ref(false)
    const editMode = ref(false)
    const currentFaq = reactive({ id: null, question: '', answer: '' })
    const faqRules = {
      question: [{ required: true, message: '请输入问题内容', trigger: 'blur' }],
      answer: [{ required: true, message: '请输入答案内容', trigger: 'blur' }]
    }
    const faqForm = ref(null)

    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
    }

    const getFaqList = async () => {
      try {
        const response = await axios.get('/api/faq')
        faqList.value = response.data.data
      } catch (error) {
        const loading = Loading.service({ fullscreen: true });
      Message.error({ message: '获取FAQ列表失败，请检查网络连接', duration: 3000 });
      loading.close();
      }
    }

    const handleEdit = (row) => {
      editMode.value = true
      Object.assign(currentFaq, row)
      showAddDialog.value = true
    }

    const handleDelete = async (id) => {
      try {
        await axios.delete(`/api/faq/${id}`)
        faqList.value = faqList.value.filter(item => item.id !== id)
        Message.success('删除成功')
      } catch (error) {
        const loading = Loading.service({ fullscreen: true });
      Message.error({ message: '删除失败，请稍后重试', duration: 3000 });
      loading.close();
      }
    }

    const handleSave = async () => {
      try {
        const isValid = await new Promise(resolve => {
          faqForm.value.validate(resolve)
        })
        if (!isValid) return

        let response
        if (editMode.value) {
          response = await axios.put(`/api/faq/${currentFaq.id}`, currentFaq)
        } else {
          response = await axios.post('/api/faq', currentFaq)
        }

        if (editMode.value) {
          const index = faqList.value.findIndex(item => item.id === currentFaq.id)
          faqList.value.splice(index, 1, response.data.data)
        } else {
          faqList.value.push(response.data.data)
        }

        showAddDialog.value = false
        Object.assign(currentFaq, { id: null, question: '', answer: '' })
        editMode.value = false
      } catch (error) {
        const loading = Loading.service({ fullscreen: true });
      Message.error({ message: error.response?.data?.message || '保存失败，请稍后重试', duration: 3000 });
      loading.close();
      }
    }

    onMounted(() => {
      getFaqList()
    })

    return {
      faqList,
      searchQuery,
      filteredFaqs,
      paginatedFaqs,
      showAddDialog,
      editMode,
      currentFaq,
      faqRules,
      faqForm,
      currentPage,
      pageSize,
      handleSizeChange,
      handleCurrentChange,
      handleEdit,
      handleDelete,
      handleSave,
      getFaqList
    }
  }
}
</script>

<style scoped>
.el-table {
  margin-top: 16px;
}

.el-dialog .el-form {
  padding: 20px 40px;
}
</style>